package com.tuuzed.android.sqlite.internal;


import android.support.annotation.NonNull;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TableInfos {
    private static Map<Class<?>, TableInfo> tableInfoMap = new ConcurrentHashMap<>();
    private static Map<Class<?>, ColumnInfo> primaryKeyColumnInfoMap = new ConcurrentHashMap<>();

    @NonNull
    public static TableInfo getTableInfo(@NonNull Class<?> tableClass) {
        TableInfo tableInfo = tableInfoMap.get(tableClass);
        if (tableInfo == null) {
            tableInfo = TableInfo.create(tableClass);
            if (tableInfo == null) {
                throw new IllegalArgumentException(tableClass.getName() + " Not labeled by @Table");
            }
            tableInfoMap.put(tableClass, tableInfo);
        }
        return tableInfo;
    }

    @NonNull
    public static ColumnInfo getPrimaryKeyColumn(Class<?> tableClass) {
        ColumnInfo columnInfo = primaryKeyColumnInfoMap.get(tableClass);
        if (columnInfo == null) {
            TableInfo tableInfo = getTableInfo(tableClass);
            for (ColumnInfo it : tableInfo.columnInfos) {
                if (it.primaryKey != null) {
                    columnInfo = it;
                    break;
                }
            }
            if (columnInfo == null) {
                throw new RuntimeException(tableClass.getName() + " Not marked primary key");
            }
            primaryKeyColumnInfoMap.put(tableClass, columnInfo);
        }
        return columnInfo;
    }
}
